//
//  CHEmotionHelper.m
//  ChildHoodStemp
//
//  Created by 日东 罗 on 13-10-10.
//
//
#define HMRecentFilepath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"recent_emotions.data"]

#import "CHEmotionHelper.h"
#import "MicroDef.h"
#import "EMotionModel.h"
#import "MJExtension.h"
static CHEmotionHelper *sharedInstance = nil;
/** 默认表情 */
static NSArray *_defaultEmotions;
/** 最近表情 */
static NSMutableArray *_recentEmotions;


@interface CHEmotionHelper ()



@end

@implementation CHEmotionHelper

+(CHEmotionHelper*)sharedInstance
{
    @synchronized(self)
    {
        if (!sharedInstance) {
            sharedInstance = [[CHEmotionHelper alloc] init];
            sharedInstance.emotions = [NSMutableArray array];
            [sharedInstance.emotions addObjectsFromArray:[self defaultEmotions]];
        }
    }
    return sharedInstance;
}

- (void)dealloc
{
    
}

- (id)init
{
    self = [super init];
    if (self) {

        
        
        }
    return self;
}


- (EMotionModel *)getFileNameByWord:(NSString *)word
{
    __block EMotionModel *returnStr = nil;//(NSString *)[_fileNameDictionary objectForKey:word];
    
    
    [self.emotions enumerateObjectsUsingBlock:^(EMotionModel *model, NSUInteger idx, BOOL *stop) {
       
        if ([model.chs isEqualToString:word]) {
            returnStr = model;
            *stop = YES;
        }

    }];
    return returnStr;
}

- (BOOL)findEmotionByText:(NSString *)text
{
    for (EMotionModel *model in self.emotions) {
        if ([model.chs isEqualToString:text]) {
            return YES;
        }
    }
    return NO;

}

+ (NSArray *)defaultEmotions
{
    if (!_defaultEmotions) {
        NSString *plist = [[NSBundle mainBundle] pathForResource:@"EmotionIcons/default/defaultinfo.plist" ofType:nil];
        _defaultEmotions = [EMotionModel objectArrayWithFile:plist];
        [_defaultEmotions makeObjectsPerformSelector:@selector(setDirectory:) withObject:@"EmotionIcons/default"];
    }
    return _defaultEmotions;
}

+ (NSArray *)recentEmotions
{
    if (!_recentEmotions) {
        // 去沙盒中加载最近使用的表情数据
        _recentEmotions = [NSKeyedUnarchiver unarchiveObjectWithFile:HMRecentFilepath];
        if (!_recentEmotions) { // 沙盒中没有任何数据
            _recentEmotions = [NSMutableArray array];
        }
    }
    return _recentEmotions;
}

// Emotion -- 戴口罩 -- Emoji的plist里面加载的表情
+ (void)addRecentEmotion:(EMotionModel *)emotion
{
    // 加载最近的表情数据
    [self recentEmotions];
    
    // 删除之前的表情
    [_recentEmotions removeObject:emotion];
    
    // 添加最新的表情
    [_recentEmotions insertObject:emotion atIndex:0];
    
    // 存储到沙盒中
    [NSKeyedArchiver archiveRootObject:_recentEmotions toFile:HMRecentFilepath];
}



@end
